using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model.Bom;
using WPF_MVVM_Test.Services.Bom;

namespace WPF_MVVM_Test.MVVM_ViewModel.Bom
{
    public class ProductSelectViewModel : BaseViewModel
    {
        private readonly ProductService _productService;
        private string _materialNumberFilter = "";
        private int _currentPageIndex = 1;
        private int _pageSize = 12;
        private int _totalCount = 0;
        private int _totalPage = 0;
        private bool _isLoading = false;
        private ProductEntity? _selectedProduct;

        public ProductSelectViewModel()
        {
            _productService = new ProductService();
            ProductItems = new ObservableCollection<ProductEntity>();

            SearchCommand = CreateCommand(ExecuteSearch);
            RefreshCommand = CreateCommand(ExecuteRefresh);
            PreviousPageCommand = CreateCommand(ExecutePreviousPage, CanExecutePreviousPage);
            NextPageCommand = CreateCommand(ExecuteNextPage, CanExecuteNextPage);
            FirstPageCommand = CreateCommand(ExecuteFirstPage, CanExecuteFirstPage);
            LastPageCommand = CreateCommand(ExecuteLastPage, CanExecuteLastPage);

            _ = LoadProductDataAsync();
        }

        public ObservableCollection<ProductEntity> ProductItems { get; }

        public string MaterialNumberFilter
        {
            get => _materialNumberFilter;
            set => SetProperty(ref _materialNumberFilter, value);
        }

        public int CurrentPageIndex
        {
            get => _currentPageIndex;
            set
            {
                if (SetProperty(ref _currentPageIndex, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                }
            }
        }

        public int TotalCount
        {
            get => _totalCount;
            set
            {
                if (SetProperty(ref _totalCount, value))
                {
                    OnPropertyChanged(nameof(PageInfo));
                }
            }
        }

        public int TotalPage
        {
            get => _totalPage;
            set => SetProperty(ref _totalPage, value);
        }

        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        public string PageInfo
        {
            get
            {
                if (IsLoading) return "正在加载数据...";
                if (TotalCount == 0) return "暂无数据";
                return $"共 {TotalCount} 条记录，第 {CurrentPageIndex} 页，共 {TotalPage} 页";
            }
        }

        public ProductEntity? SelectedProduct
        {
            get => _selectedProduct;
            set => SetProperty(ref _selectedProduct, value);
        }

        public ICommand SearchCommand { get; }
        public ICommand RefreshCommand { get; }
        public ICommand PreviousPageCommand { get; }
        public ICommand NextPageCommand { get; }
        public ICommand FirstPageCommand { get; }
        public ICommand LastPageCommand { get; }

        private async void ExecuteSearch()
        {
            CurrentPageIndex = 1;
            await LoadProductDataAsync();
        }

        private async void ExecuteRefresh()
        {
            await LoadProductDataAsync();
        }

        private async void ExecutePreviousPage()
        {
            if (CanExecutePreviousPage())
            {
                CurrentPageIndex--;
                await LoadProductDataAsync();
            }
        }

        private async void ExecuteNextPage()
        {
            if (CanExecuteNextPage())
            {
                CurrentPageIndex++;
                await LoadProductDataAsync();
            }
        }

        private async void ExecuteFirstPage()
        {
            if (CanExecuteFirstPage())
            {
                CurrentPageIndex = 1;
                await LoadProductDataAsync();
            }
        }

        private async void ExecuteLastPage()
        {
            if (CanExecuteLastPage())
            {
                CurrentPageIndex = TotalPage;
                await LoadProductDataAsync();
            }
        }

        private bool CanExecutePreviousPage() => CurrentPageIndex > 1 && !IsLoading;
        private bool CanExecuteNextPage() => CurrentPageIndex < TotalPage && !IsLoading;
        private bool CanExecuteFirstPage() => CurrentPageIndex > 1 && !IsLoading;
        private bool CanExecuteLastPage() => CurrentPageIndex < TotalPage && !IsLoading;

        private async Task LoadProductDataAsync()
        {
            try
            {
                IsLoading = true;

                var queryParams = new ProductQueryParams
                {
                    MaterialNumber = MaterialNumberFilter,
                    PageIndex = CurrentPageIndex,
                    PageSize = _pageSize
                };

                var result = await _productService.GetProductListAsync(queryParams);

                if (result.IsSuc)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        ProductItems.Clear();
                        int index = (CurrentPageIndex - 1) * _pageSize + 1;
                        foreach (var item in result.Data.Data)
                        {
                            item.Index = index++;
                            ProductItems.Add(item);
                        }

                        TotalCount = result.Data.TotalCount;
                        TotalPage = result.Data.TotalPage;
                    });
                }
                else
                {
                    MessageBox.Show($"获取产品数据失败: {result.Msg}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载产品数据失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                IsLoading = false;
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _productService?.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}